//
//  HubuQueryDetailViewController.m
//  iHubu2
//
//  Created by hanshui on 12-11-2.
//  Copyright (c) 2012年 hanshui. All rights reserved.
//

#import "HubuQueryDetailViewController.h"
#import "ASIHTTPRequest.h"
#import "OPACConstant.h"
#import "RegexKitLite.h"
#import "DomainCustomCell.h"

@interface HubuQueryDetailViewController ()

@end

@implementation HubuQueryDetailViewController
@synthesize bookTitle1, domainListTableView;
@synthesize notDataReturnLabel, waitingView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)showBookInfo:(NSString *)marcNo title:(NSString *)bookTitle {
    if(![self isViewLoaded]) {
        [self loadView];
    }
    
    self.bookTitle1 = bookTitle;
    //获取最新的新闻的内容
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://59.68.64.61:8080/opac/item.php?marc_no=%@", marcNo]];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    
    [request setDidFinishSelector:@selector(requestCompleted:)];
    [request setDidFailSelector:@selector(requestError:)];
    [request setTimeOutSeconds:10];
    [request setDelegate:self];
    [request startAsynchronous];
}



- (void)requestCompleted:(ASIHTTPRequest *)request
{
   NSMutableData *webData = [[NSMutableData alloc] init];
   [webData appendData:[request responseData]];
    NSString *theXML = [[NSString alloc] initWithBytes:[webData mutableBytes]
    											length:[webData length]
    											  encoding:NSUTF8StringEncoding];
    //NSLog(@"webData:%@", theXML);
    //    NSLog(@"webData2:%@", [OPACViewController replaceUnicode:theXML]);
    //    NSString *responseString = [[request responseString] dataUsingEncoding:NSUTF8StringEncoding];
    //    NSLog(@"responseString:%@", responseString);
    [self clearHTMLData2Array:theXML];
    
//    NSString *responseString = [request responseString];
//    NSLog(@"news:%@", responseString);
//    [self clearHTMLData2Array:responseString];
}

- (void)requestError:(ASIHTTPRequest *)request {
    NSError *error = [request error];
    NSLog(@"error:%@", error);
    [waitingView stopAnimating];
}

- (void) showNotDataReturn {
    [waitingView stopAnimating];
    [notDataReturnLabel setHidden:NO];
}

- (void) clearHTMLData2Array:(NSString *) sourceCode {
    if ( sourceCode == nil || [sourceCode isEqualToString:@""]) {
        [self showNotDataReturn];
        return;
    }
    
    if( domainListArray == nil) {
        domainListArray = [[NSMutableArray alloc] initWithCapacity:2];
    } else {
        [domainListArray removeAllObjects];
    }
    
    NSRange listBooksBegin = [sourceCode rangeOfString:BOOK_DETAIL_ITEM_BEGIN];
    int i = 0;
    while ((listBooksBegin.location != NSNotFound)) {
        NSRange listBooksEnd = [sourceCode rangeOfString:BOOK_DETAIL_ITEM_END options:nil range:NSMakeRange(listBooksBegin.location, sourceCode.length - listBooksBegin.location)];
        
        if(listBooksEnd.location == NSNotFound) {
            break;
        }
        
//        NSLog(@"item[%d]=%@", i++, [sourceCode substringWithRange:NSMakeRange(listBooksBegin.location + listBooksBegin.length, listBooksEnd.location - listBooksBegin.location - listBooksBegin.length)]);
        
        NSString *domainData = [sourceCode substringWithRange:NSMakeRange(listBooksBegin.location + listBooksBegin.length, listBooksEnd.location - listBooksBegin.location - listBooksBegin.length)];
        NSRange domainSep = [domainData rangeOfString:BOOK_DETAIL_DOMAIN_SEP];
        if(domainSep.location != NSNotFound) {
            NSString *domainTitle = [domainData substringWithRange:NSMakeRange(0, domainSep.location)];
            domainTitle = [HubuQueryDetailViewController replaceUnicode:domainTitle];
            NSString *domainValue = [domainData substringFromIndex:domainSep.location];
            domainValue = [HubuQueryDetailViewController replaceUnicode:domainValue];
//            NSLog(@"%@=%@", domainTitle, domainValue);
            
            [domainListArray addObject:[[NSArray alloc] initWithObjects:domainTitle, domainValue, nil]];
        }
        
        listBooksBegin = [sourceCode rangeOfString:BOOK_DETAIL_ITEM_BEGIN options:nil range:NSMakeRange(listBooksEnd.location, sourceCode.length - listBooksEnd.location)];
    }
    
    if([domainListArray count] < 2) {
        [self showNotDataReturn];
    } else {
        [domainListTableView reloadData];
        [waitingView stopAnimating];
    }
}

-(IBAction)backClick:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


+ (NSString *)replaceUnicode:(NSString *)unicodeStr {
	//<[^>]*>
    NSString *tempStr1 = [unicodeStr stringByReplacingOccurrencesOfRegex:@"<[^>]*>" withString:@""];
	tempStr1 = [tempStr1 stringByReplacingOccurrencesOfString:@"&#x" withString:@"\\U"];
    tempStr1 = [tempStr1 stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@" "];
    tempStr1 = [tempStr1 stringByReplacingOccurrencesOfString:@";" withString:@""];
    //NSString *tempStr1 = [tempStr1 stringByReplacingOccurrencesOfRegex:@"&#x[a-z0-9]{4};" withString:@"abc"];
	NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
	NSString *tempStr3 = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
	NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
	NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData
                                                           mutabilityOption:NSPropertyListImmutable
                                                                     format:NULL
                                                           errorDescription:NULL];
	
	//NSLog(@"Output = %@", returnStr);
	
	return [[returnStr stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@"\n"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}


#pragma mark -
#pragma mark Table View Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //NSLog(@"bookCount:%d", [bookObjectArray count]);
    return [domainListArray count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    /*
     static NSString *CellTableIdentifier = @"CellTableIdentifier";
     
     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
     CellTableIdentifier];
     if (cell == nil) {
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
     reuseIdentifier: CellTableIdentifier] autorelease];
     }
     cell.selectionStyle = UITableViewCellSelectionStyleNone;
     cell.textLabel.font = [UIFont systemFontOfSize:18];
     cell.textLabel.textColor = [UIColor colorWithRed:0.2 green:0.4 blue:0.4 alpha:1.0];
     OPACBookObjects *opacItem = [bookObjectArray objectAtIndex:[indexPath row]];
     cell.textLabel.text = [opacItem.bookTitle stringByReplacingOccurrencesOfRegex:@"&#[0-9]{4};" withString:@" "];
     
     
     return cell;
     */
    static NSString *CellTableIdentifier = @"CellTableIdentifier1";
    DomainCustomCell *cell = (DomainCustomCell *)[tableView dequeueReusableCellWithIdentifier:
                                                            CellTableIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"DomainCustomCell" owner:self options:nil] objectAtIndex:0];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSArray *domainItem = [domainListArray objectAtIndex:[indexPath row]];
    cell.title.textColor = [UIColor colorWithRed:0.2 green:0.4 blue:0.4 alpha:1.0];
    cell.title.text = [domainItem objectAtIndex:0];
    cell.content.text = [domainItem objectAtIndex:1];
    
    return cell;
}

-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 48;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    HubuQueryDetailViewController *hubuQueryDetailViewController = [[HubuQueryDetailViewController alloc] initWithNibName:@"HubuQueryDetailViewController" bundle:nil];
//    
//    OPACBookObjects *opacItem = [bookObjectArray objectAtIndex:[indexPath row]];
//    [hubuQueryDetailViewController showBookInfo:opacItem.marcNo title:opacItem.bookTitle];
//    
//    //NSDate *object = _objects[indexPath.row];
//    //self.detailViewController.detailItem = object;
//    [self.navigationController pushViewController:hubuQueryDetailViewController animated:YES];
//    [hubuQueryDetailViewController release];
    
}
@end
